package com.stone.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.stone.model.Admin;
import com.stone.model.Provider;
import com.stone.model.ProviderStone;
import com.stone.model.Stone;
import com.stone.service.ILoggerService;
import com.stone.service.IProviderService;
import com.stone.service.IProviderStoneService;
import com.stone.service.IStoneService;
import com.stone.serviceimpl.LoggerService;
import com.stone.utils.EncryptUtil;
import com.stone.utils.LogConstrants;
import com.stone.utils.Page;

public class ProviderAction extends ActionSupport {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 908224356540771453L;
	
	/**
	 * 一些Service
	 */
	private IProviderService providerService;
	private IStoneService stoneService;
	private IProviderStoneService providerStoneService;
	private ILoggerService logService = new LoggerService();
	private Provider provider;
	private File iconFile;
	private String uploadDir; //上传头像的路径
	private String iconFileName; //文件尾坠
	private Long providerId;	// 具体的供应商ID
	private String type="all";
	private String providerName; 
	private int existFlag; 
	private String flag ; // add  or update!!
	private boolean hrefFlag = false;
	private String[] phoneList = null;
	private String[] faxList = null;
	private String[] emailList = null;
	private String[] websiteList = null;
	private List<Stone> stonesList; // 用于显示的供应商列表
	private List<ProviderStone> psList;//供应商的石材中间表
	private List<Stone> selectedStonesList;//已经选择的石材列表
	private List<Provider> providerList;
	private List<Integer> completeList;
	private int listSize;
	private String selectedStones; //所选中的石头
	private String timeStr;
	private Page page;		//分页显示所用的page bean
	private Integer pageNo = 1;
	private Integer pageSize = 20;
	private int pageno;
	private int totalpageno;
	private int currentpageno;
	private String query;
	private boolean mainSearch = false;
	private boolean hasQueue = false;
	/*Max Number Of Recently Visit Stone*/
	private final int MAXRECENTLY = 3;
	
	private String username = "";
	private String password = "";
	private String error = "";
	private String oldPassword = "";
	private boolean chagePwdFlag;
	
	private static Logger logger = Logger.getLogger("供应商");
	
	private int year;
	private int month;
	private String displayFlag;
	
	//-------------------------------------------
	
	public String checkNameExist(){
		List<Provider> list = providerService.findProviderByName(providerName);
		existFlag = list.size();
		if(flag.equals("update")){
			if(existFlag == 1){
				try{
					Provider p = list.get(0);
					if(p.getId().equals(providerId)){
						existFlag--;
					}
				}catch(Exception ex){
				//	System.out.println("无法获取更新的ID");
				}
			}
		}
		return SUCCESS;
	}
	
	public String checkUsernameExist(){
		Provider provider = providerService.findProviderByUsername(providerName);
		if(provider != null){
			existFlag = 1;
			if(flag.equals("update")){
				if(provider.getId().compareTo(providerId) == 0)
					existFlag--;
				}
		}
		else
			existFlag = 0;
		return SUCCESS;
	}
	
	public String submitDisplay()
	{
		Provider p = providerService.findProviderById(providerId);
		if(displayFlag.equals("yes"))
		{
			p.setDisplayFlag(new Integer(1));
		
		}
		else if(displayFlag.equals("no"))
		{
			p.setDisplayFlag(new Integer(0));
		
		}
		providerService.updateProvider(p);
		return SUCCESS;
	}
	
	public String findProviderListAjax(){
		if(providerName != null && !providerName.equals("")){
			page = providerService.findProviderByName(providerName , pageno ,pageSize);
		}else{
			this.page = this.providerService.findAllProviders(pageno, pageSize);
		}
		providerList = page.getList();
		listSize = providerList.size();
		return "success";
	}
	

	/**
	 * 保存供应商
	 */
	public String saveProvider(){
		try {
			provider.setPhoto(updateIcon());//设置头像
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		provider.setShortable(provider.getShortable().toUpperCase());
		DateFormat df = new SimpleDateFormat("yyyy-MM");
		try {
			Date date = df.parse(year + "-" + month);
			provider.setFoundationTime(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//phoneList = provider.getPhone().split("#");
		provider = providerService.addProvider(provider);
		
		return SUCCESS;
	}
	
	
	/**
	 * 更新石材的介绍，取得所有石材的列表，下一步
	 * @return
	 */
	public String addProviderStep2(){
		Provider p = providerService.findProviderById(provider.getId());
		p.setDescription(provider.getDescription());
		providerService.updateProvider(p);//先更新
		providerService.createNewIndex(ServletActionContext.getRequest().getRealPath("")); //更新索引
		stonesList = stoneService.findStonePageByName("", 1, 50).getList(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		providerId = provider.getId();
		return SUCCESS;
	}
	/**
	 * 取得所有选中的石材，下一步
	 * @return
	 */
	public String addProviderStep3(){
		String[] stoneIdList = selectedStones.split(";");
		stonesList = null;
		stonesList = new ArrayList<Stone>();
		for(String stoneId : stoneIdList){
			stonesList.add(stoneService.getStoneById(Long.parseLong(stoneId.trim())));
		}
		return SUCCESS;
	}
	
	/**
	 * 取得 供应商-石材 供应情况的填写情况
	 * @return
	 */
	public String addProviderStep4(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		provider = providerService.findProviderById(providerId);
		String[] stoneIdList = selectedStones.split(";");
		for(String stoneId : stoneIdList){
			ProviderStone ps = new ProviderStone();
			ps.setProvider(provider); //设置供应商
			Stone temp = stoneService.getStoneById(Long.parseLong(stoneId.trim()));
			ps.setStone(temp);//设置石材
		
			if(!request.getParameter("rawMaxprice"+stoneId).toString().trim().equals(""))
				ps.setRawMaxprice(Float.valueOf((request.getParameter("rawMaxprice"+stoneId).toString().trim())));
			else
				ps.setRawMaxprice(null);
			if(!request.getParameter("rawMinprice"+stoneId).toString().trim().equals(""))
				ps.setRawMinprice(Float.valueOf((request.getParameter("rawMinprice"+stoneId).toString()).trim()));
			else
				ps.setRawMinprice(null);
			if(!request.getParameter("slabMaxprice"+stoneId).toString().trim().equals(""))
				ps.setSlabMaxprice(Float.valueOf((request.getParameter("slabMaxprice"+stoneId).toString().trim())));
			else
				ps.setSlabMaxprice(null);
			if(!request.getParameter("slabMinprice"+stoneId).toString().trim().equals(""))
				ps.setSlabMinprice(Float.valueOf((request.getParameter("slabMinprice"+stoneId).toString()).trim()));
			else
				ps.setSlabMinprice(null);
//			ps.setMaxprice(Float.valueOf((request.getParameter("maxprice"+stoneId).toString().trim())));
//			ps.setMinprice(Float.valueOf((request.getParameter("minprice"+stoneId).toString()).trim()));
			ps.setQuality(request.getParameter("quality"+stoneId).toString());
			ps.setQuantity(request.getParameter("quantity"+stoneId).toString().trim());
			ps.setWeight(Float.valueOf((request.getParameter("weight"+stoneId).toString()).trim()));
			providerStoneService.addProviderStone(ps);
		}
		
		//------- log记录
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"增加了供应商: " + provider.getName());
		logService.log(((Admin)session.get("admin")).getUsername(), "增加了供应商: " + provider.getName(), LogConstrants.PROVIDER_ADD);
		//清空数据
		provider = null; 
		stonesList = null;
	
		return SUCCESS;
	}
	//---------------------------------------------------------------------------------
	
	public String toUpdateProvider(){
		//供应商
		if(providerId == null) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			Provider p = (Provider) session.get("provider");
			if(p != null)
				providerId = p.getId();
		}
		
		provider = providerService.findProviderById(providerId);
		
		if(type.equals("totext")){
			Date foundationTime = provider.getFoundationTime();
			if(foundationTime != null)
			{	
				Calendar cal = Calendar.getInstance();
				cal.setTime(foundationTime);
				this.year = cal.get(Calendar.YEAR);
				this.month = cal.get(Calendar.MONTH)+1;
			}//Calendar 返回的结果少1
			//System.out.println("year : " + year);
			//System.out.println("month : " + month);
			if(provider.getPhone() != null)
				phoneList = provider.getPhone().split("#");
			if(provider.getFax() != null)
				faxList = provider.getFax().split("#");
			if(provider.getEmail() != null)
				emailList = provider.getEmail().split("#");
			if(provider.getWebSite() != null)
				websiteList = provider.getWebSite().split("#");
			return "totxt";
		}else if( type.equals("tophoto")){
			return "tophoto";
		}else if(type.equals("todescript")){
			return "todescript";
		}else if(type.equals("toselstone")){
			stonesList = stoneService.findStonePageByName("", currentpageno, 50).getList();
			psList = providerStoneService.findAllPrividerStoneByProviderId(providerId);
			selectedStonesList = new ArrayList<Stone>();
			for(ProviderStone ps : psList){
				selectedStonesList.add(ps.getStone());
				stonesList.remove(ps.getStone());
			}
			return "toselstone";
		} else if(type.equals("toaccount")) {
			return "toaccount";
		} else{
			return SUCCESS;
		}
	}
	
	/**
	 * 更新供应商信息
	 * @return
	 */
	public String updateProvider(){
		if(type.equals("text")){
			Provider p = providerService.findProviderById(providerId);
//			provider.setShortable(provider.getShortable().toUpperCase());
//			provider.setDescription(p.getDescription());
//			provider.setPhoto(p.getPhoto());
//			provider.setProviderStones(p.getProviderStones());
//			provider.setDisplayFlag(p.getDisplayFlag());
			p.setAddress(provider.getAddress());
			p.setBigSlab(provider.getBigSlab());
			p.setCity(provider.getCity());
			p.setContactPerson(provider.getContactPerson());
			p.setDuty(provider.getDuty());
			p.setEmail(provider.getEmail());
			p.setEquipment(provider.getEquipment());
			p.setFactoryArea(provider.getFactoryArea());
			p.setFax(provider.getFax());
			Date date = new Date();
			date.setYear(year-1900);//year应去掉1900的基数
			date.setMonth(month-1);//month是0-11之间的数
			p.setFoundationTime(date);
			p.setName(provider.getName());
			p.setOther(provider.getOther());
			p.setPhone(provider.getPhone());
			p.setProduct(provider.getProduct());
			p.setProvince(provider.getProvince());
			p.setRawStone(provider.getRawStone());
			p.setRegisterCapital(provider.getRegisterCapital());
			p.setShortable(provider.getShortable().toUpperCase());
			p.setShortDescription(provider.getShortDescription());
			p.setStaffSize(provider.getStaffSize());
			p.setStandardSlab(provider.getStandardSlab());
			p.setWebSite(provider.getWebSite());
			p.setLnglat(provider.getLnglat());
			providerService.updateProvider(p);
		}else if( type.equals("descpt")){
			Provider p = providerService.findProviderById(providerId);
			p.setDescription(provider.getDescription());
			providerService.updateProvider(p);
		}else if(type.equals("photo")){
			provider = providerService.findProviderById(providerId);
			try {
				provider.setPhoto(updateIcon());
			} catch (IOException e) {
				e.printStackTrace();
			}
			providerService.updateProvider(provider);
		}else if(type.equals("sel")){
			String[] stoneIdList = selectedStones.split(";");
			
			stonesList = null;
			stonesList = new ArrayList<Stone>();
			for(String stoneId : stoneIdList){
				if(!stoneId.equals(""))
					stonesList.add(stoneService.getStoneById(Long.parseLong(stoneId.trim()))); //得到选择的所有的石头
			}
			
			psList = null; 
			psList = providerStoneService.findAllPrividerStoneByProviderId(providerId); //得到目前供应商-石材  的关联表
			
			List<ProviderStone> tempList = new ArrayList<ProviderStone>();
			tempList = providerStoneService.findAllPrividerStoneByProviderId(providerId);;
			for(int i=0; i<tempList.size(); i++){
				ProviderStone ps = tempList.get(i);
				if(ps.getStone() == null)
					continue;
				String id = ps.getStone().getId().toString().trim();
				for(String stoneId : stoneIdList){
					if(stoneId.trim().equals(id)){
						stonesList.remove(ps.getStone());	//剩下的 stoneList 就是要新插入的石材
						psList.remove(ps);				//剩下的就是被删除掉了的 映射表
						break;
					}
				}//完成查询  
			}
			tempList = null;
			
			for(int j=0 ; j < psList.size(); j++){
				ProviderStone psd = psList.get(j);
			//	System.out.println("删除某记录:" + psd.getProvider().getName() +" -- " + psd.getStone().getChineseName());
				providerStoneService.deleteProviderStone(psd);
			}
			
			for(int k=0; k < stonesList.size();k++){
				ProviderStone psn = new ProviderStone(); 
				psn.setProvider(providerService.findProviderById(providerId));
				psn.setStone(stonesList.get(k));
				//System.out.println("增加某记录:" + psn.getProvider().getName() +" -- " + psn.getStone().getChineseName());
				providerStoneService.addProviderStone(psn);
			}
			stonesList = null;
			psList = null;
			psList = providerStoneService.findAllPrividerStoneByProviderId(providerId);
			return "next";
		}else if(type.equals("setps")){
			
			HttpServletRequest request = ServletActionContext.getRequest();
			psList = providerStoneService.findAllPrividerStoneByProviderId(providerId);
			for(int x=0;x<psList.size();x++){
				ProviderStone pst = psList.get(x);
				if(!request.getParameter("rawMaxprice"+pst.getId()).toString().trim().equals(""))
					pst.setRawMaxprice(Float.valueOf((request.getParameter("rawMaxprice"+pst.getId()).toString().trim())));
				else
					pst.setRawMaxprice(null);
				if(!request.getParameter("rawMinprice"+pst.getId()).toString().trim().equals(""))
					pst.setRawMinprice(Float.valueOf((request.getParameter("rawMinprice"+pst.getId()).toString()).trim()));
				else
					pst.setRawMinprice(null);
				if(!request.getParameter("slabMaxprice"+pst.getId()).toString().trim().equals(""))
					pst.setSlabMaxprice(Float.valueOf((request.getParameter("slabMaxprice"+pst.getId()).toString().trim())));
				else
					pst.setSlabMaxprice(null);
				if(!request.getParameter("slabMinprice"+pst.getId()).toString().trim().equals(""))
					pst.setSlabMinprice(Float.valueOf((request.getParameter("slabMinprice"+pst.getId()).toString()).trim()));
				else
					pst.setSlabMinprice(null);
				pst.setQuality(request.getParameter("quality"+pst.getId()).toString());
				pst.setQuantity(request.getParameter("quantity"+pst.getId()).toString().trim());
				pst.setWeight(Float.valueOf((request.getParameter("weight"+pst.getId()).toString()).trim()));
				providerStoneService.updateProviderStone(pst);
			}
		} else if(type.equals("account")) {
			Provider p = providerService.findProviderById(providerId);
			if(provider.getUsername() != null && ! provider.getUsername().equals("") && provider.getPassword() != null && ! provider.getPassword().equals("")) {
				p.setUsername(provider.getUsername());
				p.setPassword(EncryptUtil.md5(provider.getPassword()));
				providerService.updateProvider(p);
			}
		}
		
		//------- log记录
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"更新了供应商: " + providerService.findProviderById(provider.getId()).getName());
		logService.log(((Admin)session.get("admin")).getUsername(), "更新了供应商: " + providerService.findProviderById(provider.getId()).getName(), LogConstrants.PROVIDER_UPDATE);
		
		providerService.createNewIndex(ServletActionContext.getRequest().getRealPath(""));
		providerId = provider.getId();
		return SUCCESS;
	}
	/**
	 * 删除某供应商
	 * @return
	 */
	public String deleteProvider(){
		
		//------- log记录
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"删除了供应商: " + providerService.findProviderById(providerId).getName());
		//logService.log(((Admin)session.get("admin")).getUsername(), "删除了供应商: " + providerService.findProviderById(providerId).getName(), LogConstrants.PROVIDER_UPDATE);
		
		providerService.deleteProvider(providerService.findProviderById(providerId));
		providerService.createNewIndex(ServletActionContext.getRequest().getRealPath(""));
		return SUCCESS;
	}
	
	public String findProvider(){
		provider = providerService.findProviderById(providerId);
		if(provider.getPhone()!=null)
			phoneList = provider.getPhone().split("#");
		if(provider.getFax()!=null)
			faxList = provider.getFax().split("#");
		if(provider.getEmail()!=null)
			emailList = provider.getEmail().split("#");
		if(provider.getWebSite()!=null)
			websiteList = provider.getWebSite().split("#");
		//page = providerStoneService.findAllPrividerStoneByProviderIdByPage(providerId, 1, 5);
		page = providerStoneService.findDisplayAllProviderStoneByProviderIdByPage(providerId, 1, 5);
		return SUCCESS;
	}
	
	public String findProvidersByPage(){
		if(hrefFlag){
			try {
				providerName = new String(ServletActionContext.getRequest().getParameter("providerName").getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if(providerName != null && !providerName.equals("")){
			page = providerService.findProviderByName(providerName, pageNo, pageSize);
		}else{
			page = providerService.findAllProviders(pageNo, pageSize);
		}
		completeList=new ArrayList<Integer>();
		faxList = new String[page.getList().size()];
		websiteList = new String[page.getList().size()];
		for(int i = 0 ; i < page.getList().size(); i ++ )
		{
			Provider provider = (Provider)page.getList().get(i);
			
			int complete = CalculateCompleteness(provider);
			completeList.add(complete);
			
			faxList[i] = provider.getFax().split("#")[0];
		//	emailList[i] = provider.getEmail().split("#")[0];
			websiteList[i] = provider.getWebSite().split("#")[0];
		}
		hrefFlag = false;
		return SUCCESS;
	}
	
	private int CalculateCompleteness(Provider provider) {
		float fz = 0;
		float fm = 0;
		if(provider.getName()!=null&&!provider.getName().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getShortable()!=null&&!provider.getShortable().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getProvince()!=null&&!provider.getProvince().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getCity()!=null&&!provider.getCity().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getAddress()!=null&&!provider.getAddress().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getRegisterCapital()!=null&&!provider.getRegisterCapital().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getFoundationTime()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getStaffSize()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getFactoryArea()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getEquipment()!=null&&!provider.getEquipment().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getBigSlab()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getRawStone()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getStandardSlab()!=null)
		{fz++;fm++;}
		else
			fm++;
		if(provider.getContactPerson()!=null&&!provider.getContactPerson().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getDuty()!=null&&!provider.getDuty().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getPhone()!=null&&!provider.getPhone().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getFax()!=null&&!provider.getFax().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getWebSite()!=null&&!provider.getWebSite().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getEmail()!=null&&!provider.getEmail().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getShortDescription()!=null&&!provider.getShortDescription().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getProduct()!=null&&!provider.getProduct().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getOther()!=null&&!provider.getOther().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getPhoto()!=null&&!provider.getPhoto().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getDescription()!=null&&!provider.getDescription().equals(""))
		{fz++;fm++;}
		else
			fm++;
		if(provider.getProviderStones()!=null&&!provider.getProviderStones().isEmpty())
		{fz++;fm++;}
		else
			fm++;
		if(provider.getLnglat()!=null&&!provider.getLnglat().isEmpty())
		{fz++;fm++;}
		else
			fm++;
		return (int) (fz*100/fm);
	}

	public String findProviderPageByName(){
		page = providerService.findProviderByName(providerName, pageNo, pageSize);
		return SUCCESS;
	}

	/**
	 * 上传的文件 返回其文件名
	 * @return
	 * @throws IOException 
	 */
	public String updateIcon() throws IOException{
		if(iconFile != null){
			String fileName =  System.currentTimeMillis()+iconFileName;	//设置名字
			BufferedOutputStream bos = null; //文件输出流
		    BufferedInputStream bis = null; //文件输入流
		    FileInputStream fis = new FileInputStream(iconFile);
			bis = new BufferedInputStream(fis);
			String outPath = ServletActionContext.getServletContext().getRealPath(uploadDir);
			FileOutputStream fos = new FileOutputStream(new File(outPath,fileName));
			bos = new BufferedOutputStream(fos);
			byte[] buf = new byte[1024*10];
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			buf = null;
			bos.flush();
			bos.close(); //关闭输出流
			bis.close(); //关闭输入流
			return fileName;
		}else{
			return "none";
		}
	}
	
	public String highSearchProvider(){
		String path = ServletActionContext.getRequest().getRealPath("");
		if(providerService.createIndex(path)){
//			long begin = new Date().getTime();
			if(this.pageno!=1){
				this.pageno=getPageNo(this.pageno,this.totalpageno);
			}	
			try {
				if(!mainSearch)
					this.query = new String(ServletActionContext.getRequest().getParameter("query").getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			long begin = new java.util.Date().getTime();
			if(query.trim().equals(""))
			{
				//page = providerService.findAllProviders(pageno, 15);
				page = providerService.findAllDisplayProviders(pageNo, 15);
			}
			else
				page = providerService.getHighSearchProvider(path,query,pageno,15);
			DecimalFormat df = new DecimalFormat("#0.000");
			long end = new java.util.Date().getTime();
			double time = (double) (end - begin) / 1000;
			timeStr = df.format(time);
			this.totalpageno=page.getTotalPages();
			this.currentpageno=page.getCurrentPage();
			setQueue();
			checkPopular();
		}
		return "success";
	}
	/**
	 * 通过页面传来的pageno来决定当前页数
	 * @param pageNo
	 * @param totalpageno
	 * @return
	 */
	public int getPageNo(int pageNo,int totalpageno){
		if(pageNo>totalpageno){
			pageNo = totalpageno;
		}
		if(pageNo<=0){
			return 1;
		}
		return pageNo;
	}
	/**
	 *  check whether the popular stones are in the session 
	 */
	private void checkPopular(){
		Map session = ActionContext.getContext().getSession();
		if(session.get("popular")==null){
			//List<Stone> popularStones = stoneService.getVisitMostStones(1, 6).getList();
			List<Stone> popularStones = stoneService.getVisitMostDisplayStones(1, 6).getList();
			session.put("popular", popularStones);
		}
	}
	/**
	 * Get Visit Stone from Session Scop
	 */
	private void setQueue(){
		Map session = ActionContext.getContext().getSession();
		Queue<Stone> queue = (Queue<Stone>)session.get("recent");
		if(queue==null){
			queue = new ArrayBlockingQueue<Stone>(MAXRECENTLY);
			session.put("recent", queue);
		}
		hasQueue = (queue.size()>0)?true:false;
	}
	
	
	public String login(){
		boolean flag = providerService.check(username, EncryptUtil.md5(password));
		if(flag){
			Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("provider", providerService.findProviderByUsername(username));
			logger.fatal("供应商：" + username + "登录到供应商后台系统...");
			username = "";
			password = "";
			return SUCCESS;
		}else{
			error = ">>>用户名或密码错误，请重新登录!";
			username = "";
			password = "";
			return ERROR;
		}
	}
	
	public String logout(){
		username = "";
		password = "";
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal("供应商：" + ((Provider)session.get("provider")).getUsername()+"退出系统...");
		session.remove("provider");
		session.clear();
		return SUCCESS;
	}
	
	public String toLogin(){
		username = "";
		password = "";
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove("provider");		
		return "toProviderLogin";
	}
	
	public String changePassword(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		Provider provider = (Provider) session.get("provider");
		if(EncryptUtil.md5(oldPassword).equals(provider.getPassword())){
			provider.setPassword(EncryptUtil.md5(password));
			providerService.updateProvider(provider);
			session.put("provider", providerService.findProviderByUsername(provider.getUsername()));
			chagePwdFlag = true;
		}else{
			chagePwdFlag = false;
		}
		password = "";
		return SUCCESS;
	}
	
	//------------------------------set and  get
	public Provider getProvider() {
		return provider;
	}

	public void setProvider(Provider provider) {
		
		this.provider = provider;
	}

	public IProviderService getProviderService() {
		return providerService;
	}

	public void setProviderService(IProviderService providerService) {
		this.providerService = providerService;
	}

	public File getIconFile() {
		return iconFile;
	}

	public void setIconFile(File iconFile) {
		this.iconFile = iconFile;
	}

	public String getUploadDir() {
		return uploadDir;
	}

	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}

	public String getIconFileName() {
		return iconFileName;
	}

	public void setIconFileName(String iconFileName) {
		this.iconFileName = iconFileName;
	}

	public Long getProviderId() {
		return providerId;
	}

	public void setProviderId(Long providerId) {
		this.providerId = providerId;
	}

	public List<Stone> getStonesList() {
		return stonesList;
	}

	public void setStonesList(List<Stone> stonesList) {
		this.stonesList = stonesList;
	}
	public IStoneService getStoneService() {
		return stoneService;
	}
	public void setStoneService(IStoneService stoneService) {
		this.stoneService = stoneService;
	}
	public String getSelectedStones() {
		return selectedStones;
	}
	public void setSelectedStones(String selectedStones) {
		this.selectedStones = selectedStones;
	}

	public IProviderStoneService getProviderStoneService() {
		return providerStoneService;
	}

	public void setProviderStoneService(IProviderStoneService providerStoneService) {
		this.providerStoneService = providerStoneService;
	}

	public Integer getPageNo() {
		return pageNo;
	}

	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<ProviderStone> getPsList() {
		return psList;
	}

	public void setPsList(List<ProviderStone> psList) {
		this.psList = psList;
	}

	public List<Stone> getSelectedStonesList() {
		return selectedStonesList;
	}

	public void setSelectedStonesList(List<Stone> selectedStonesList) {
		this.selectedStonesList = selectedStonesList;
	}

	public String getTimeStr() {
		return timeStr;
	}

	public void setTimeStr(String timeStr) {
		this.timeStr = timeStr;
	}

	public int getPageno() {
		return pageno;
	}

	public void setPageno(int pageno) {
		this.pageno = pageno;
	}

	public int getTotalpageno() {
		return totalpageno;
	}

	public void setTotalpageno(int totalpageno) {
		this.totalpageno = totalpageno;
	}

	public int getCurrentpageno() {
		return currentpageno;
	}

	public void setCurrentpageno(int currentpageno) {
		this.currentpageno = currentpageno;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public boolean isMainSearch() {
		return mainSearch;
	}

	public void setMainSearch(boolean mainSearch) {
		this.mainSearch = mainSearch;
	}

	public boolean isHasQueue() {
		return hasQueue;
	}

	public void setHasQueue(boolean hasQueue) {
		this.hasQueue = hasQueue;
	}

	public String getProviderName() {
		return providerName;
	}

	public void setProviderName(String providerName) {
		this.providerName = providerName;
	}

	public int getExistFlag() {
		return existFlag;
	}

	public void setExistFlag(int existFlag) {
		this.existFlag = existFlag;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public boolean isHrefFlag() {
		return hrefFlag;
	}

	public void setHrefFlag(boolean hrefFlag) {
		this.hrefFlag = hrefFlag;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public String getDisplayFlag() {
		return displayFlag;
	}

	public void setDisplayFlag(String displayFlag) {
		this.displayFlag = displayFlag;
	}

	public String[] getPhoneList() {
		return phoneList;
	}

	public void setPhoneList(String[] phoneList) {
		this.phoneList = phoneList;
	}

	public List<Provider> getProviderList() {
		return providerList;
	}

	public void setProviderList(List<Provider> providerList) {
		this.providerList = providerList;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public boolean isChagePwdFlag() {
		return chagePwdFlag;
	}

	public void setChagePwdFlag(boolean chagePwdFlag) {
		this.chagePwdFlag = chagePwdFlag;
	}	

	public List<Integer> getCompleteList() {
		return completeList;
	}

	public void setCompleteList(List<Integer> completeList) {
		this.completeList = completeList;
	}

	public String[] getFaxList() {
		return faxList;
	}

	public void setFaxList(String[] faxList) {
		this.faxList = faxList;
	}

	public String[] getEmailList() {
		return emailList;
	}

	public void setEmailList(String[] emailList) {
		this.emailList = emailList;
	}

	public String[] getWebsiteList() {
		return websiteList;
	}

	public void setWebsiteList(String[] websiteList) {
		this.websiteList = websiteList;
	}
	
}

